const passport = require('koa-passport')
const LocalStrategy = require('passport-local').Strategy
const { requestLogin } = require('../api/user')
passport.use(
  new LocalStrategy(
    {
      usernameField: 'email',
      passwordField: 'pwd'
    },
    async function(username, password, done) {
      const { status, data } = await requestLogin({
        email: username,
        pwd: password
      })
      const item = data.data
      if (status === 200 && data.statu === 0) {
        return done(null, {
          id: item.id,
          sex: item.sex,
          email: item.email,
          name: item.name,
          avatar: item.img,
          follow: item.followNumber,
          fans: item.fansNumber
        })
      } else {
        return done(null, false, {
          message: 'error'
        })
      }
    }
  )
)

passport.serializeUser(function(user, done) {
  done(null, user)
})

passport.deserializeUser(function(user, done) {
  return done(null, user)
})

module.exports = passport
